<template>
	<el-autocomplete
		v-model="selectName"
		clearable
		:value-key="filterLabel"
		:fetch-suggestions="querySearchAsync"
		style="width: 100%"
		@select="handleSelect"
		@clear="handleClear"
	>
		<template v-slot:default="{ item }">
			<p class="f-between">
				<span>{{ item[filterLabel] }}</span>
				<span class="f12 text-gray" v-if="tipLabel">{{ item[tipLabel] }}</span>
			</p>
		</template>
	</el-autocomplete>
</template>

<script setup lang="ts">
import apiMod from '@/apiMod/index'
import bus from '@/utils/eventbus'

const emit = defineEmits(['update:modelName', 'update:modelValue', 'change'])

const props = defineProps<{
	api: string
	modelName?: string
	modelValue?: any
	filterLabel?: string
	filterKey: string
	tipLabel?: string
	paramsObj?: any
}>()


const selectName = ref(props.modelName)

watch(
	() => props.modelValue,
	() => {
		selectName.value = props.modelName
	},
	{
		immediate: true,
	}
)

let dataList: any = []
const handleSelect = (item: Record<string, any>) => {
	emit('update:modelName', item[props.filterLabel])
	emit('update:modelValue', item[props.filterKey])
	emit('change', item)
	bus.emit('remote-change', {
		api: props.api,
		value: item[props.filterKey],
		label: item[props.filterLabel],
	})
}

const querySearchAsync = (queryString: string, cb: any) => {
	if (!queryString) {
		handleSelect({})
	}
	let query: any = {
	}
	if (props.filterLabel && queryString!='null') {
		query[props.filterLabel] = queryString
	}

	getInitData(query).then((res: any) => {
		cb(res)
	})
}

const getInitData = (query = {}) => {
	return new Promise((resolve, reject) => {
		apiMod[props.api]({
      ...query,
      ...props.paramsObj,
    }).then((res: any) => {
			const data = res.data
			dataList = Array.isArray(data) ? data : data.records
			resolve(dataList)
		})
	})
}
const handleClear = () =>{
	emit('update:modelName', undefined)
	emit('update:modelValue', undefined)
}


onMounted(() => {
	getInitData({})
})
</script>

<style scoped></style>
